// 帖子和二手可以共用这个评论
import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const PostMsgSchema = new mongoose.Schema({
    content: String, // 内容
    postId: String, // 帖子id
    creatorId: String,
    creator: Object, // 留言者
    likes: {type: Object, default: {}},
    likeNum: {type: Number, default: 0},
    scores: Array,
    tags: Array,
    createTime: Number,
});

PostMsgSchema.methods.savePostMsg = function (postMsg, cb) {
    postMsg.createTime = moment().unix();
    this.model('postMsg').insertMany([postMsg], cb);
};

PostMsgSchema.methods.getPostMsgs = function (query, cb) {
    const { current, pageSize, ...leftQuery } = query;
    const postMsgModel = this.model('postMsg');
    if (leftQuery.createTime) {
        leftQuery.createTime = { $lt: leftQuery.createTime }
    }
    postMsgModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        postMsgModel.find(leftQuery).sort({createTime: -1}).skip((current - 1) * pageSize).limit(pageSize).exec((err, postMsgs) => cb(err, postMsgs, count, hasMore));
    });
};

PostMsgSchema.methods.getAllPostMsgs = function (query, cb) {
    this.model('postMsg').find(query, cb);
};

PostMsgSchema.methods.getPostMsg = function (query, cb) {
    this.model('postMsg').findOne(query, cb);
};

PostMsgSchema.methods.updatePostMsg = function (postMsg, cb) {
    const _id = postMsg._id;
    delete postMsg._id;
    this.model('postMsg').findOneAndUpdate({ _id }, { $set: postMsg }, cb);
};

PostMsgSchema.methods.removePostMsgs = function (postMsgIds, cb) {
    this.model('postMsg').remove({ _id: { $in: postMsgIds } }, cb);
};

export default db.model('postMsg', PostMsgSchema);